<?php

namespace apiend\modules\mall\models;

use Yii;
use yii\db\Exception;
use common\models\shop\ShopGoods;
use common\models\user\UserCoupon;

/**
 * 订单取消模型
 * 
 * @author emhome<emhome@163.com>
 * @since 2.0
 */
class OrderCancelForm extends \common\base\Model {

    /**
     * @var integer 下单用户ID
     */
    public $user_id;

    /**
     * @var integer 订单ID
     */
    public $id;

    /**
     * @var string 订单模型
     */
    private $_model = null;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['id'], 'required'],
            [['id', 'user_id'], 'integer'],
            [['id'], 'validateOrder'],
        ];
    }

    /**
     * 校验订单信息
     * @param string $attribute the attribute currently being validated
     */
    public function validateOrder($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $model = OrderView::find()->active()->andWhere([
            'and',
            ['id' => $this->$attribute],
            ['>=', 'status', OrderView::STATUS_DEFAULT],
        ])->one();
        if (!$model) {
            return $this->addError($attribute, '订单信息不存在或者状态已过期');
        }
        if (!$model->canCancel()) {
            return $this->addError($attribute, '当前订单状态已变更，不能取消！');
        }
        $this->_model = $model;
    }

    /**
     * 订单信息模型
     * @return OrderView|null
     */
    public function getModel() {
        return $this->_model;
    }

    /**
     * 取消订单并保存
     * @return OrderView
     */
    public function save() {
        if (!$this->validate()) {
            return $this->dumpError('订单操作失败');
        }
        $model = $this->getModel();
        $model->status = OrderView::STATUS_CANCEL;

        //回收优惠券
        $coupons = $model->usedCoupons;

        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$model->save()) {
                throw new Exception($model->getErrorMsg());
            }
            if (!empty($coupons)) {
                foreach ($coupons as $coupon) {
                    $coupon->status = UserCoupon::STATUS_DEFAULT;
                    $coupon->model = '';
                    $coupon->model_id = 0;
                    if (!$coupon->save()) {
                        throw new Exception($coupon->getErrorMsg());
                    }
                }
            }
            foreach ($model->goods as $sku) {
                $goods = ShopGoods::findOne($sku->goods_id);
                if (!$goods) {
                    continue;
                }
                $goods->stock += $sku->goods_number;
                if (!$goods->save()) {
                    throw new Exception($goods->getErrorMsg());
                }
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $msg = $e->getMessage();
            return $this->dumpError('订单取消失败，' . $msg, false);
        }
        return $model->toArray();
    }

}
